package com.rchat.pocmini.activity.location;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.airtalkee.sdk.AirtalkeeAccount;
import com.airtalkee.sdk.entity.AirContact;
import com.airtalkee.sdk.entity.AirSession;
import com.aso.common.http.bean.BaseBean;
import com.aso.common.http.delegate.HttpCallbackImpl;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.OpenClientUtil;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.account.PocAccount;
import com.rchat.pocmini.activity.bean.ClistBean;
import com.rchat.pocmini.activity.fragment.groups.GroupsPresenterImpl;
import com.rchat.pocmini.activity.listener.MediaListener;
import com.rchat.pocmini.activity.view.location.CustomDialog1;
import com.rchat.pocmini.activity.view.location.MyOrientationListener;
import com.rchat.pocmini.bean.LocationBean;
import com.rchat.pocmini.bean2eventbus.LocationReportFreqBean;
import com.rchat.pocmini.bean2eventbus.MediaListenerBean;
import com.rchat.pocmini.service.LocationReportService;
import com.rchat.pocmini.service.PocService;
import com.rchat.pocmini.session.PocAirtalkeeSessionManager;
import com.rchat.pocmini.util.SPUtil;
import com.rchat.pocmini.util.Sound;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import static android.content.Context.VIBRATOR_SERVICE;

/**
 * Created by ljd on 2017/9/28.
 */

public class LocationPresenterImpl extends LocationContract.Presenter implements MediaListener {

    private boolean isFirstLoc = true; // 是否首次定位
    private PocAccount account;
    private String groupId;
    private String groupName;
    private PocAirtalkeeSessionManager sessionManager;
    private AirSession airSession;

    private AirContact mAirContact;//自己
    private MyOrientationListener myOrientationListener;
    private int mXDirection;

    /**
     * 当前的精度
     */
    private float mCurrentAccracy;

    /**
     * 最新一次的经纬度
     */
    private double mCurrentLantitude;
    private double mCurrentLongitude;

    private LocationClient mLocClient;
    public MyLocationListener myListener;

    private Handler reqOtherLocationHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    reqOtherLocation();
                    break;
            }

        }
    };

    @Override
    public void onPStart() {
        super.onPStart();

        MediaListenerBean b1 = new MediaListenerBean();
        b1.setTarget(this.getClass(), PocService.class, "onEventBusUpdateMediaListener");
        b1.setCurrentEvent(MediaListenerBean.EVENT_REGISTER_LISTENER);
        b1.setListener(this);
        EventBus.getDefault().post(b1);

        groupId = mActivity.getIntent().getStringExtra(GroupsPresenterImpl.KEY_GROUPID);
        airSession = PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().getLockedAirSession();
        sessionManager = PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance();
        mAirContact = new AirContact();
        mAirContact.setIpocId(AirtalkeeAccount.getInstance().getUserId());
        mAirContact.setDisplayName(AirtalkeeAccount.getInstance().getUserName());
        mView.showMember(mAirContact);

        myListener = new MyLocationListener();
        mLocClient = new LocationClient(mActivity);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(10000);
        mLocClient.setLocOption(option);
        mLocClient.start();

        reqOtherLocationHandler.sendEmptyMessage(1);
    }

    @Override
    void reqLocationReport10S() {
        final LocationReportFreqBean bean = new LocationReportFreqBean();
        bean.setTarget(this.getClass(), LocationReportService.class, "onEventBusLocationReportFreqChange");
        bean.setCurrentEvent(LocationReportFreqBean.LOCATION_REPORT_10_S_FOR_ENTER_LOCATION_ACTIVITY);//2是十秒上报
        EventBus.getDefault().post(bean);
    }

    @Override
    void cancelLocationReport10S() {
        final LocationReportFreqBean bean = new LocationReportFreqBean();
        bean.setTarget(this.getClass(), LocationReportService.class, "onEventBusLocationReportFreqChange");
        int reportFreq = (int) SPUtil.get(mActivity.getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT_FREQ, -1);
        int position = 0;
        switch (reportFreq) {
            case -1:
                position = 0;
                break;
            case 5 * 1000:
                position = 1;
                break;
            case 10 * 1000:
                position = 2;
                break;
            case 30 * 1000:
                position = 3;
                break;
            case 60 * 1000:
                position = 4;
                break;
            case 3 * 60 * 1000:
                position = 5;
                break;
            case 10 * 60 * 1000:
                position = 6;
                break;
        }
        bean.setCurrentEvent(position);
        EventBus.getDefault().post(bean);
    }

    @Override
    void reqTalk() {
        sessionManager.talkRequest(airSession);
    }

    @Override
    void reqTalkRelease() {
        sessionManager.talkRelease(airSession);
    }

    @Override
    void initOrientationListener() {
        myOrientationListener = new MyOrientationListener(mActivity);
        myOrientationListener
                .setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {

                    @Override
                    public void onOrientationChanged(float x) {
//                        mView.showXDirection((int)x);
                        mXDirection = (int) x;
                        // 构造定位数据
                        LatLng latLng = new LatLng(mCurrentLantitude, mCurrentLongitude);
                        MyLocationData locData = new MyLocationData.Builder()
                                .accuracy(mCurrentAccracy)
                                // 此处设置开发者获取到的方向信息，顺时针0-360
                                .direction(mXDirection)
                                .latitude(mCurrentLantitude)
                                .longitude(mCurrentLongitude).build();
                        // 设置定位数据
                        mView.setLocationData(locData);
                        // 设置自定义图标
                        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                                .fromResource(R.drawable.icon_map_diracton_self);
                        MyLocationConfiguration configuration = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker);
                        mView.setLocationConfiguration(configuration, latLng);

                    }
                });
        myOrientationListener.start();
    }

    @Override
    void reqOtherLocation() {
        //查询其他人的位置信息
        mModel.reqOtherLocation(AirtalkeeAccount.getInstance().getUserId(), groupId, new HttpCallbackImpl<LocationBean>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(LocationBean bean) {
                ALog.d("desc = %s", bean.getDesc());
                List<ClistBean> list = new ArrayList<>();
                for (LocationBean.DataBean.ClistBean b : bean.getData().getClist()) {
                    if (b.getUserName().equals(AirtalkeeAccount.getInstance().getUserId())) {
                        continue;
                    }
                    Log.e("aaaa", b.getDisplayName());
                    ClistBean bean1 = new ClistBean();
                    bean1.setUid(b.getDisplayName());
                    bean1.setCid(b.getDirection());
                    bean1.setLongitude(b.getLongitude() + "");
                    bean1.setLatitude(b.getLatitude() + "");
                    bean1.setDirection(b.getDirection());
                    bean1.setUptime(b.getDisplayName());
                    bean1.setUsername(b.getDisplayName());
                    list.add(bean1);
                }
                if (mView != null) {
                    mView.updateOverlay(list, mAirContact);
                }
            }

            @Override
            public void onFailureResult(BaseBean bean) {
                List<ClistBean> list = new ArrayList<>();
                if (mView != null) {
                    mView.updateOverlay(list, mAirContact);
                }
                ALog.d("code = %s,message = %s", bean.getCode(), bean.getDesc());
            }

            @Override
            public void onFinish() {

            }

        });
        reqOtherLocationHandler.sendEmptyMessageDelayed(1, 10000);
    }

    @Override
    void oriLocation() {
        LatLng ll = new LatLng(mCurrentLantitude, mCurrentLongitude);
        mView.targetToLatLng(ll, false);
    }

    @Override
    void startNavigation(Marker endMarker, Marker startMarker) {
        try {
            Intent i1 = new Intent();
            // 驾车路线规划
            StringBuilder startSB = new StringBuilder(startMarker.getPosition().latitude + "");
            startSB.append(",");
            startSB.append(startMarker.getPosition().longitude + "");

            StringBuilder endSB = new StringBuilder(endMarker.getPosition().latitude + "");
            endSB.append(",");
            endSB.append(endMarker.getPosition().longitude + "");

            i1.setData(Uri.parse("baidumap://map/direction?origin=" + startSB.toString() + "&destination=" + endSB.toString() + "&mode=driving"));
            mActivity.startActivity(i1);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            showNoMapDialog();
        }
    }

    private Dialog memberDetailDialog;
    private RelativeLayout memberDetailLayout;
    private TextView memberName;
    private TextView memberId;

    @Override
    void showMemberDetailDialog(final Marker marker, List<AirContact> mMemberList, final Marker startMarker) {
        if (marker.getExtraInfo() == null) {
            return;
        }
        if (memberDetailDialog == null) {
            LayoutInflater inflaterDl = LayoutInflater.from(mActivity);
            memberDetailLayout = (RelativeLayout) inflaterDl.inflate(R.layout.dialog_member_detail, null);
            memberName = (TextView) memberDetailLayout.findViewById(R.id.tv_displayName);
            memberId = (TextView) memberDetailLayout.findViewById(R.id.tv_id);

            //对话框
            memberDetailDialog = new AlertDialog.Builder(mActivity).create();
            memberDetailDialog.setCanceledOnTouchOutside(true);
        }

        String id = marker.getExtraInfo().getString("id");

        Button talk_btn_navi = (Button) memberDetailLayout.findViewById(R.id.talk_btn_navi);
        if (id.equals(PocAccount.getUserId())) {
            memberName.setText(mAirContact.getDisplayName());
            if (PocAccount.isUserNameChanged()) {
                memberId.setText(PocAccount.getNewUserName());
            } else {
                memberId.setText(PocAccount.getUserName());
            }

            talk_btn_navi.setVisibility(View.INVISIBLE);
        } else {
            for (AirContact airContact : mMemberList) {
                if (airContact.getIpocId().equals(id)) {
                    memberName.setText(airContact.getDisplayName());
                    memberId.setText(airContact.getIpocId());
                    talk_btn_navi.setVisibility(View.VISIBLE);
                    break;
                }
            }
        }
        talk_btn_navi.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                memberDetailDialog.dismiss();
                showNavDialog(marker, startMarker);
            }
        });

        memberDetailDialog.show();
        memberDetailDialog.getWindow().setContentView(memberDetailLayout);
        Window dialogWindow = memberDetailDialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        WindowManager m = mActivity.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 0.75); // 宽度设置为屏幕的0.85
        p.height = (int) (d.getHeight() * 0.60);
        p.dimAmount = 0.2f;      //设置黑暗度
        dialogWindow.setAttributes(p);
    }

    @Override
    void horizonListOnItemClick(AdapterView<?> parent, View view, int position, long id, ConcurrentHashMap<String, Marker> markers) {
        AirContact airContact = (AirContact) parent.getItemAtPosition(position);
        if (airContact.getIpocId().equals(AirtalkeeAccount.getInstance().getUserId())) {
            LatLng ll = new LatLng(mCurrentLantitude, mCurrentLongitude);
            mView.targetToLatLng(ll, false);
        } else {
            if (markers.containsKey(airContact.getIpocId())) {
                LatLng ll = markers.get(airContact.getIpocId()).getPosition();
                mView.targetToLatLng(ll, false);
            }
        }
    }

    private CustomDialog1 naviDialog, noMapDialog;

    private void showNavDialog(final Marker endMarker, final Marker startMarker) {
        naviDialog = new CustomDialog1(mActivity, "使用百度地图进行导航？",
                "确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                naviDialog.dismiss();
                startNavigation(endMarker, startMarker);
            }
        }, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                naviDialog.dismiss();
            }
        });

        naviDialog.show();
    }

    private void showNoMapDialog() {
        if (noMapDialog == null) {
            noMapDialog = new CustomDialog1(mActivity, "您尚未安装百度地图app或app版本过低，无法导航。",
                    "下载", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    noMapDialog.dismiss();
                    OpenClientUtil.getLatestBaiduMapApp(mActivity);
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    noMapDialog.dismiss();
                }
            });
        }

        noMapDialog.show();
    }

    @Override
    public void onMediaStateTalkPreparing(AirSession var1) {
//        callSystemVibrator();
    }

    @Override
    public void onMediaStateTalk(AirSession var1) {
        mView.showTalkIv(R.drawable.ic_location_talk_pressed);
    }

    @Override
    public void onMediaStateTalkEnd(AirSession var1, int var2) {
        Sound.playSound(Sound.PLAYER_MEDIA_ME_OFF, mActivity);
        mView.showTalkIv(R.drawable.ic_location_talk);
    }

    @Override
    public void onMediaStateListen(AirSession var1, AirContact var2) {

    }

    @Override
    public void onMediaStateListenEnd(AirSession var1) {

    }

    @Override
    public void onMediaStateListenVoice(AirSession var1) {

    }

    @Override
    public void onMediaQueue(AirSession var1, ArrayList<AirContact> var2) {

    }

    @Override
    public void onMediaQueueIn(AirSession var1) {

    }

    @Override
    public void onMediaQueueOut(AirSession var1) {

    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (mView == null) {
                ALog.eTag("LocationPresenterImpl", "界面已销毁");
                return;
            }
            // map view 销毁后不在处理新接收的位置
            if (location == null) {
                return;
            }
            mCurrentLantitude = location.getLatitude();
            mCurrentLongitude = location.getLongitude();
            mCurrentAccracy = location.getRadius();
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mXDirection)
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            // 设置定位数据
            mView.setLocationData(locData);
            // 设置自定义图标
            BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                    .fromResource(R.drawable.icon_map_diracton_self);
            MyLocationConfiguration configuration = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker);

            mView.setLocationConfiguration(configuration, latLng);

            // 第一次定位时，将地图位置移动到当前位置
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                mView.targetToLatLng(ll, true);
            }

        }

        public void onReceivePoi(BDLocation poiLocation) {

        }
    }

    @Override
    public void onPDestroy() {
        reqOtherLocationHandler.removeMessages(1);
        myOrientationListener.setOnOrientationListener(null);
        myOrientationListener.stop();
        /**
         * author:sudf
         * data:2017.12.06
         * bug:界面退出后，监听没有移除，导致myListener中的mView空指针异常
         *     mLocClient 没有stop，界面反复进出后，出现leaked异常
         */
        mLocClient.unRegisterLocationListener(myListener);
        if (mLocClient.isStarted()) {
            mLocClient.stop();
        }
        MediaListenerBean b1 = new MediaListenerBean();
        b1.setTarget(this.getClass(), PocService.class, "onEventBusUpdateMediaListener");
        b1.setCurrentEvent(MediaListenerBean.EVENT_UNREGISTER_LISTENER);
        b1.setListener(this);
        EventBus.getDefault().post(b1);
        super.onPDestroy();
    }

//    //震动
//    private void callSystemVibrator() {
//        Vibrator vibrator;
//        vibrator = (Vibrator) mActivity.getSystemService(VIBRATOR_SERVICE);
//        vibrator.vibrate(new long[]{0, 150}, -1);
//    }
}
